package service

import (
	"fmt"
	"im/global"
	"im/model/chat"
	"im/utils"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

type ChatService struct{}

var initMsg = "欢迎进入聊天系统"

// ws升级器: 将http 请求转成 ws
var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func (s *ChatService) WsHandler(c *gin.Context) {
	// 校验用户是否登录
	fmt.Println("test ......")
	r := c.Request
	token := r.Header.Get(global.TOKEN_HEADER)
	userId, _ := utils.ParseUserIdByTokenData(token)
	log.Printf("userId: %v", userId)
	conn, err := upgrader.Upgrade(c.Writer, r, nil)
	if err != nil {
		log.Println(err)
	}
	client := &chat.Client{
		Hub:    global.Hub,
		Conn:   conn,
		Send:   make(chan []byte),
		UserId: userId,
	}
	// 协程：实现发送和接收消息逻辑
	go client.ReadDump()
	go client.WriteDump()

	// 添加到conns集合中
	global.Hub.Register <- client
	// client.Hub.Clients[client] = true

	// 对该用户发送欢迎信息
	client.Send <- []byte(initMsg)
	fmt.Println("client: ", client)
}
